import sys

import cherrypy
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.api import memcache

from mymoney.controllers import PayeeHandler, CategoryHandler, AccountHandler

# patch sys memcache module locations to use GAE memcache
sys.modules['memcache'] = memcache

def restricted_to_admin():
    user = users.get_current_user()
    
    if user != None and user.nickname() != "nicolas.pied":
        raise cherrypy.HTTPError("401 Unauthorized")
    #if cherrypy.request.login not in users:

cherrypy.tools.restricted_to_admin = cherrypy.Tool('on_start_resource', restricted_to_admin)

def http_methods_allowed(methods=['GET', 'HEAD']):
    method = cherrypy.request.method.upper()
    if method not in methods:
        cherrypy.response.headers['Allow'] = ", ".join(methods)
        raise cherrypy.HTTPError(405)

cherrypy.tools.allow = cherrypy.Tool('on_start_resource', http_methods_allowed)

class HelloWorld:
    def index(self):
        user = users.get_current_user()
        
        if user:
            return "user is defined : " + user.nickname()
        else:
            current_url = cherrypy.url(qs=cherrypy.request.query_string)
            raise cherrypy.HTTPRedirect(users.create_login_url(current_url))
    index.exposed = True

#cherrypy.quickstart(HelloWorld())

def main():
#    app = cherrypy.tree.mount(HelloWorld(),"/")
#    wsgiref.handlers.CGIHandler().run(app)

    # Some global configuration; note that this could be moved into a
    # configuration file
    #cherrypy.config.update({
    #    'tools.restricted_to_admin.on': True,
    #    'tools.encode.on': True, 
    #    'tools.encode.encoding': 'utf-8',
    #    'tools.decode.on': True,
    #    'tools.trailing_slash.on': True,
    #    #'tools.staticdir.root': '/static', #os.path.abspath(os.path.dirname(__file__)),
    #    'tools.sessions.storage_type': "memcached",
    #    'tools.sessions.servers': ['memcached://'],
    #    'tools.sessions.name': 'mymoney.appengine.com',
    #    'tools.sessions.clean_thread': True,
    #    'tools.session.timeout': 10, # ten minute session timeout, not sure if this works
    #})
    
    settings = {
        '/favicon.ico': {  
            'tools.staticfile.on': True,  
            'tools.staticfile.filename': '/static/favicon.ico',  
        }
    }
    
    #cherrypy.config.update(settings)        
    
    # [/favicon.ico]
    # tools.staticfile.on = True
    # tools.staticfile.filename = "/static/favicon.ico"
    
#    cherrypy.quickstart(Root(data), '/', {
#        '/static': {
#            'tools.staticdir.on': True,
#            'tools.staticdir.dir': 'static'
#        }
#    })
    
    root = HelloWorld()
    root.account = AccountHandler()
    root.payee = PayeeHandler()
    root.category = CategoryHandler()
        
    app = cherrypy.tree.mount(root,"/", settings)
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == '__main__':
    main()
